<template>
  <a-layout class="allLayout">
    <a-layout-content>
      <unit-table
        ref="unitTable"
        :columns="this.$staticMenu.userListColumns"
        :size="pageSize"
        :params="tableParams"
        :sizeOptions="pageSizeOptions"
        :type="tableType"
        :url="tableUrl"
        rowKeyName="id"
        @onSelect="tableOnSelect"
      >
            <!-- 补充搜索条件 -->
      <a-row slot="searchCri">
        <a-col :span="5">
          <a-input v-model="tableParams.username" class="searchCriteria" placeholder="姓名/账户名（仅支持数字、字母和汉字）"  @keydown.native="keydown($event)" onkeyup="value=value.replace(/[\s+`~!@#$%^&*()_\-+=<>?:{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/,'') " onbeforepaste="clipboardData.setData('text',clipboardData.getData('text').replace(/^[a-zA-Z0-9_()（）\u4e00-\u9fa5]{1,50}$/,''))"  />
        </a-col>
        <a-col :span="3">
          <a-select v-model="tableParams.role" class="searchCriteria">
            <a-select-option
              v-for="(item, key) of role"
              :value="item.id"
              :key="item.id"
            >{{item.roleName}}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="3">
          <a-select v-model="tableParams.userStatus" class="searchCriteria">
            <a-select-option
              v-for="(item, key ) of status"
              :value="item.value"
              :key="item.key"
            >{{item.title}}</a-select-option>
          </a-select>
        </a-col>
        <a-col :span="3">
            <a-tree-select
                v-model="tableParams.areacode"
                class="searchCriteria"
                :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
                :tree-data="this.treeData"
                style="width: 100%"
                tree-default-expand-all
              >
           </a-tree-select>
        </a-col>

        <a-col :span="10" style="text-align: right;">
          <a-button type="primary" @click="criteriaSearch">
            <a-icon type="search" />查询
          </a-button>
          <a-button @click="clearCriteria">
            <a-icon type="sync" />重置
          </a-button>
        </a-col>
      </a-row>
        <!-- 补充表格操作 -->
        <div slot='tableAct' class="actionBtn">
          <a-button type="primary" @click="addUser">
            <a-icon type="plus"/>
            添加
          </a-button>
        </div>
        <!-- end -->
        <span slot="roleName" slot-scope="props">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{props.record.permissions == undefined ? "": props.record.permissions.toString()}}</span>
              </template>
              <span class="ellipsis">{{props.record.permissions  == undefined ? "": props.record.permissions.toString()}}</span>
            </a-tooltip>
        </span>
        <span slot="departmentName" slot-scope="props">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{props.record.departmentName  == undefined ? "": props.record.departmentName.toString()}}</span>
              </template>
              <span class="ellipsis">{{props.record.departmentName ==undefined ? "": props.record.departmentName.toString()}}</span>
            </a-tooltip>
        </span>
         <span slot="areaCodeName" slot-scope="props">
            <a-tooltip placement="top">
              <template slot="title">
                <span>{{ props.record.areaCodeName==undefined ? "":props.record.areaCodeName.toString() }}</span>
              </template>
              <span class="ellipsis">{{props.record.areaCodeName==undefined ? "":props.record.areaCodeName.toString() }}</span>
            </a-tooltip>
        </span>
        <span slot="statusSwitch" slot-scope="props">
          <span v-if="props.record.userStatus==1" class="text-success">
            已审批
          </span>
          <span v-else-if="props.record.userStatus==-1" class="text-danger">
            未审批
          </span>
          <span v-else-if="props.record.userStatus==0" class="text-warning">
            已拒绝
          </span>
        </span>
        <!-- 补充表格每行的操作 -->
        <span slot="tableRowAct" slot-scope="props">
					<a @click="editUser(props.record)" v-if="props.record.userStatus==1  && props.record.id>5">
						<span class="ant-tag ant-tag-blue">
							<a-icon type="form"/> 修改
						</span>
					</a>
					<a-divider type="vertical" v-if="props.record.userStatus==1" />
					<a @click="deleteUser(props.record)" v-if="props.record.userStatus==1  && props.record.id>5">
						<span class="ant-tag ant-tag-volcano">
							<a-icon type="delete"/> 删除
						</span>
					</a>
            <a @click="approvalUser(props.record)" v-if="props.record.userStatus==-1">
              <span class="ant-tag ant-tag-green">
                <a-icon type="form"/> 审批
              </span>
            </a>
            <a-divider type="vertical" v-if="props.record.userStatus==-1"/>
            <a @click="rejectUser(props.record)" v-if="props.record.userStatus==-1">
              <span class="ant-tag ant-tag-volcano">
               <a-icon type="delete"/> 拒绝
              </span>
            </a>
            <a @click="clearException(props.record)" v-if="props.record.loginFailed>2">
              <span class="ant-tag ant-tag-blue">
                <a-icon type="form"/> 解除异常
              </span>
            </a>
				</span>
      </unit-table>
      <modal
        ref="userModalForm"
        :title="modalTitle"
        :visible="modalVisible"
        @cancel="handleCancel"
        @ok="handleOk"
        :readonly="isWrite"
        :validator="validatorForm"
      >
      </modal>
      <a-modal
        ref="userAppModalForm"
        :title="appModalTitle"
        :visible="appModalVisible"
        @cancel="handleAppCancel"
        @ok="handleAppOk"
      >
      </a-modal>
    </a-layout-content>
  </a-layout>
</template>

<script>
import {GETALLUSER,DELETEUSER,GETALLROLELIST,REGIONTREE,REJECTUSER,UPDATEUSER} from '@/../static/js/apis.js'
import unitTable from "@/common/table"
import modal from "./components/userModal"
import aModal from "./components/userApprovalModal"
import {userForm, userForm1} from "@/../static/js/formValidators.js"
import _ from "lodash" //引入lodash：封装了诸多对字符串，数组，对象等常见数据类型的处理函数
export default {
  inject: ['reload'],                                 //注入App里的reload方法
  name: 'approval',
  components: {
    unitTable,
    modal,
    aModal
  },
  data() {
    return {
      tableSelectedKeys: [],
      tableUrl: GETALLUSER.url,  //调用表格组件，必须参数，后台数据接口
      tableType: GETALLUSER.type,  //调用表格组件，必须参数，后台方法方法（get，post）
      pageSize: 15,
      pageSizeOptions: ['15', '20', '40'],
      tableParams: {
        username: '',
        role: -1,
        areacode:-1,
        userStatus:"-100",
        loginFailed:0
      },
      /*modal参数*/
      modalTitle: '',     //modal标题
      modalVisible: false,    //modal关闭打开控制器
      appModalTitle:'',
      appModalVisible:false,
      isWrite:'',
      validatorForm: userForm,
      role:[],
      status:[],
      treeData:[]
    }
  },
  mounted () {
    if(this.$route.query.type==='WSP'){
      this.tableParams.userStatus='-1'
      this.criteriaSearch()
    }else if(this.$route.query.type==='YSP'){
      this.tableParams.userStatus='1'
      this.criteriaSearch()
    }else if(this.$route.query.type==='YCZH'){
      this.tableParams.loginFailed=3
      this.criteriaSearch()
    }
  },
  methods: {
    keydown(e){
      if(e.keyCode==32){
        e.returnValue=false
      }
    },
    getStaticData() {
      let self = this
      self.status = [ {
        title:'全部状态',
        key: '-1',
        value:"-100"
      },{
        title:'未审批',
        key:'0',
        value:'-1'
      },{
        title:'已审批',
        key:'1',
        value:'1'
      },{
        title:'已拒绝',
        key:'2',
        value: '0'
      }
      ]
      REGIONTREE('', function (res) {
        var arr=[{"title":"全部区域","key":-1,"value":-1}]
        var arr3 = arr.concat(res.obj);
        self.treeData = arr3
      })
      GETALLROLELIST('', function (res) {
        self.role.push({"roleName":"全部角色","id":-1})
        for (var i = 0; i <res.data.length; i++) {
          var vote = {};
          vote.id = res.data[i].id;
          vote.roleName = res.data[i].roleName;
          self.role.push(vote);
        }
      })
    },
    /*表格checkbox选中事件*/
    tableOnSelect(selectedRowKeys, selectedRows) {
      this.tableSelectedKeys = selectedRowKeys
    },
    /* 查询按钮*/
    criteriaSearch () {
      // this.$refs.unitTable.fetch(1)
      this.$refs.unitTable.fetch(1)
    },
    /*重置按钮 */
    clearCriteria () {
      this.tableParams.username = ''
      this.tableParams.role = -1
      this.tableParams.areacode = -1
      this.tableParams.userStatus = '-100'
      this.tableParams.loginFailed=0
      this.criteriaSearch()
    },
    addUser () {
      this.modalTitle = '添加用户'
      this.modalVisible = true
      this.isWrite = false
      this.validatorForm = userForm
    },
    clearException (record) {
      let values = {
        id: record.id,
        username: record.username,
        loginFailed: 0
      }
      let self =this
      self.$confirm({
        title: '确定要清除账户( ' + record.realName + ' [' + record.username + '] ' + ')的异常并允许用户访问已授权的应用吗？',
        content: '清除后操作不可取消，点击“ 确定 ”按钮清除异常，确认框关闭。',
        onOk () {
          UPDATEUSER(values, function(res){
            if(res.code=='200'){
              self.$message.success('用户异常清除成功！')
              self.reload()
            }else{
              self.$message.error('用户异常清除失败，请稍后再试！')
            }
          })
        }
      })
    },
    editUser(record) {
      this.modalTitle = "修改用户"
      this.modalVisible = true
      this.isWrite=true
      this.validatorForm = userForm1
      //form的setFieldsValue方法放入参数与form中对应，可少不可多，用以下方法进行筛选
      const pickArr = ['username', 'password', 'role', 'areaCodeName', 'department', 'security','permissions','realName']
      const formShowInfo = _.pick(record, pickArr)
      //把数据放入modal，要在form加载完成后
      this.$nextTick(() => {
        this.$refs.userModalForm.form.setFieldsValue(formShowInfo)
      })
    },
    deleteUser(record) {

      let param={
        id:record.id
      }
      self.$confirm({
        title: '确定要删除该用户吗？',
        content: '删除后该用户将不可恢复，点击“ 确定 ”按钮删除该用户，确认框关闭。',
        onOk () {
          DELETEUSER(param, function(res){
              if(res.code=='200'){
                self.$message.success('用户删除成功！')
                self.reload()
              }else{
                self.$message.error('用户删除失败，请稍后再试！')
              }
          })
        }
      })
    },
    approvalUser(record) {
      this.appModalTitle = "审批用户"
      this.appModalVisible = true
      let pickArr = []
      if(record.role===null){
        pickArr = ['username','areaCodeName','security','permissions','realName']
      }else{
        pickArr = ['username','role','areaCodeName','security','permissions','realName']
      }

      const formShowInfo = _.pick(record, pickArr)
      //把数据放入modal，要在form加载完成后
      this.$nextTick(() => {
        this.$refs.userAppModalForm.form.setFieldsValue(formShowInfo)
      })
    },
    rejectUser(record) {
      let self=this
      let param={
        id:record.id
      }
      self.$confirm({
        title: '确定要拒绝该用户吗？',
        content: '点击“ 确定 ”按钮拒绝该用户，确认框关闭。',
        onOk () {
          REJECTUSER(param, function (res) {
            if (res.code == '200') {
              self.$message.success(res.message)
              self.reload()
            } else {
              self.$message.error(res.message)
            }
          })
        }
      })
    },
    /*modal确定事件*/
    handleOk(e) {
      this.modalVisible = false
    },
    /*modal取消事件*/
    handleCancel(e) {
      this.modalVisible = false
    },
    /*modal确定事件*/
    handleAppOk(e) {
      this.appModalVisible = false
    },
    /*modal取消事件*/
    handleAppCancel(e) {
      this.appModalVisible = false
    }
  },
  created () {
    this.getStaticData()
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .allLayout {
    margin: 30px;
  }

  .ant-layout-content {
    background-color: white;
  }

  .actionBtn button:not(:last-child),
  .ant-row button:not(:last-child) {
    margin-right: 20px;
  }

  .action {
    color: #1890ff
  }
  .searchCriteria{
    width:80%;
  }

  .ant-tag{
    margin: 5px;
  }
</style>
